package com.epoint.mobileoa.ui.audiorecord;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.tools.AlertHelp;
import com.epoint.mobileoa.tools.DateHelp;
import com.epoint.mobileoa.tools.SDCard;
import com.epoint.mobileoa.tools.ToastHelp;

/**
 * 音频录制
 * 
 * @author lilin
 * @date 2011-12-7 上午08:12:43
 */
public class AudioRecordView extends SuperView implements OnClickListener {

	private File recFile;// 录音生成的文件

	private List<String> recList = new ArrayList<String>();// 存放 录音文件路径的List
	private AudioListAdp recAdapter;// 录音文件Listview的适配器
	private String tempName = "";// 录音文件名前缀
	private ListView recListView;// 存放录音的ListView
	public static List<String> chooseFileList = new ArrayList<String>();// 选中文件列表

	private Handler handler;
	private ProgressDialog progressdialog;// 滚动条
	// private String pathString;// 录音文件路径
	public static String index = "";// 从适配器传过来的选中的Index
	private Chronometer chronometer;// 计时器
	private TextView status;// 当前状态
	// private int position;
	// private List<String> fileList = new ArrayList<String>();
	//
	// private ListView fileListView;
	// // private SeekBar seekbar;// 滑动滚动条
	//
	// // private boolean isfirst = true;
	//
	// private boolean isStopThread = true;
	// @SuppressWarnings("unused")
	// private int MSG_REFRESH = 1;
	// @SuppressWarnings("unused")
	// private int duration;// 播放时长
	// 播放service
	// private PlayService playService;
	// private FreshThread freshThread;

	private Button rec_btn;// 录音按钮
	// 底部按钮菜单
	private Button confirm_btn;// 确定按钮
	private Button delMarked_btn;// 删除标记按钮
	private Button delAll_btn;// 删除全部按钮

	int recType = 1;// 采用MediaRecorder录制，2采用audioRecord录制
	private MediaRecorder mediaRec;// // 一般用来录制视频
	// 使用AudioRecord录音
	private AudioRecord audioRecord = null;
	// 这里的值注意了，写的不好，可能实例化AudioRecord对象的时候，会出错,取决于硬件设备
	private static int frequency = 44100;// 录制频率，单位hz,44100,11025,8000
	private static int channel = AudioFormat.CHANNEL_CONFIGURATION_MONO;// 设置声道
	private static int encodingBitRate = AudioFormat.ENCODING_PCM_16BIT;// 设置编码
	private static final int recorder_bpp = 16;
	private int recBufSize = 0;
	private boolean isRecording = false;// 录音标志位
	private String tempFilePath;// 临时文件的路径
	private String saveFilePath;// 保存文件的路径
	private static final String temp_file = "record_temp.raw";// 零时文件名
	private Thread recThread = null;// 录音线程

	private void initView() {
		tempFilePath = SDCard.getFileSavePath(getString(R.string.rec_savepath))
				+ temp_file;
		progressdialog = ProgressDialog.show(AudioRecordView.this, null,
				"正在努力加载...", true);
		status = (TextView) findViewById(R.id.status_text);
		status.setText("未录音");
		recListView = (ListView) findViewById(R.id.rec_list);
		confirm_btn = (Button) findViewById(R.id.radio_button0);
		delMarked_btn = (Button) findViewById(R.id.radio_button1);
		delAll_btn = (Button) findViewById(R.id.radio_button2);
		rec_btn = (Button) findViewById(R.id.rec_btn);
		confirm_btn.setOnClickListener(this);
		delMarked_btn.setOnClickListener(this);
		delAll_btn.setOnClickListener(this);
		rec_btn.setOnClickListener(this);
		rec_btn.setTag("record");
		rec_btn.setText("开始录音");
		handler = new Handler();
		freshListView();// 初始化录音列表
		findViewById(R.id.reclayout).setBackgroundResource(
				R.drawable.audiorec_bg);
		chronometer = (Chronometer) findViewById(R.id.chronometer);
		// 录音列表单击事件
		recListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// 调用系统自带的播放器
				File file = new File(recList.get(arg2));
				playRec(file);
			}
		});
	}

	// 初始化recList
	public void freshListView() {
		new Thread() {
			public void run() {
				doInHandler();
			};
		}.start();
	}

	public void doInHandler() {
		if (!SDCard.getFileSavePath(getString(R.string.rec_savepath))
				.toString().equals(null)) {
			recList.clear();
			handler.post(new Runnable() {
				public void run() {
					// 取得指定位置的文件,添加到recList中
					File home = new File(getString(R.string.rec_savepath));
					if (home.listFiles(new AudioFileFilter()).length > 0) {
						for (File file : home.listFiles(new AudioFileFilter())) {
							// 将录音文件的路径添加进recList
							recList.add(file.getPath().toString());
						}
					}
					recAdapter = new AudioListAdp(getApplicationContext(),
							recList);
					recListView.setAdapter(recAdapter);
					// 关闭滚动条
					progressdialog.dismiss();
				}
			});
		} else {
			ToastHelp.showToast(getApplicationContext(), "请插入内存卡！");
		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.radio_button0:
		// 确定选中
		{
			if (rec_btn.getTag().equals("stop")) {
				ToastHelp.showToast(getApplicationContext(), "请停止播放，否则按钮不可用！");
			} else {
				chooseFileList.clear();

				if (index.equals("") || index.equals(null)) {
				} else {
					String msg = "";
					String id[] = index.split(";");
					for (int i = 0; i < id.length; i++) {
						String path = recList.get(Integer.valueOf(id[i]));
						chooseFileList.add(path);
						msg = msg + path + "\n";
					}
					// 清空index
					index = "";
					// /ToastHelp.showToast(getApplicationContext(), msg);
					if (chooseFileList.size() > 1) {
						ToastHelp.showToast(this, "选择的录音不要超过1一个！");
						chooseFileList.clear();
					} else {
						finish();
					}
				}

			}
		}

			break;
		case R.id.radio_button1:
		// 删除选中
		{
			if (rec_btn.getTag().equals("stop")) {
				ToastHelp.showToast(getApplicationContext(), "请停止播放，否则按钮不可用！");
			} else {
				if (recList.size() > 0)
				// 判断有数据可删除
				{
					if (index.equals("") || index.equals(null)) {
						Toast.makeText(getApplicationContext(), "请选择要删除的录音!",
								5000).show();
					} else {
						Builder builder = new AlertDialog.Builder(
								AudioRecordView.this);
						builder.setTitle("确定要删除选中吗？");
						builder.setIcon(R.drawable.epoint2);
						builder.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										String id[] = index.split(";");
										for (int i = 0; i < id.length; i++) {
											String path = recList.get(Integer
													.valueOf(id[i]));
											SDCard.deleteFile(path);
										}
										// 清空index
										index = "";

										// 刷新
										freshListView();
										ToastHelp.showToast(
												getApplicationContext(),
												"删除选定成功!");
									}
								});
						builder.setNegativeButton("取消", null);
						builder.create().show();
					}
				} else {
					Toast.makeText(getApplicationContext(), "列表为空！", 5000)
							.show();
				}

			}
		}

			break;
		case R.id.radio_button2:
		// 删除全部
		{
			if (rec_btn.getTag().equals("stop")) {
				ToastHelp.showToast(getApplicationContext(), "请停止播放，否则按钮不可用！");
			} else {
				if (recList.size() > 0)
				// 判断有数据可删除
				{
					Builder builder = new AlertDialog.Builder(
							AudioRecordView.this);
					builder.setTitle("确定要删除全部吗？");
					builder.setIcon(R.drawable.epoint2);
					builder.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									for (int i = 0; i < recList.size(); i++) {
										String path = recList.get(i);
										SDCard.deleteFile(path);
									}

									// 刷新
									freshListView();
									ToastHelp.showToast(
											getApplicationContext(), "删除全部成功!");

								}
							});
					builder.setNegativeButton("取消", null);
					builder.create().show();

				} else {

				}

			}
		}
			break;
		case R.id.rec_btn:
		// 录音按钮
		{
			RecordMethod();
		}
			break;

		default:
			break;
		}
	}

	private void RecordMethod() {
		// 开始录音
		if (rec_btn.getTag().equals("record")) {
			rec_btn.setText("停止录音");
			rec_btn.setTag("stop");
			if (!SDCard.getFileSavePath(getString(R.string.rec_savepath))
					.toString().equals(null)) {
				chronometer.setBase(SystemClock.elapsedRealtime());// 设置开始讲时时间
				chronometer.start();// 开始记时
				startRec();// 开始录音
				status.setText("正在录音...");
				ToastHelp.showToast(getApplicationContext(), "开始录音...");
			} else {
				ToastHelp.showToast(getApplicationContext(), "请插入内存卡！");
			}
		}
		// 停止录音
		else if (rec_btn.getTag().equals("stop")) {
			rec_btn.setText("开始录音");
			rec_btn.setTag("record");
			stopRecord();
			status.setText("未录音");
			chronometer.stop();// 停止计时
			chronometer.setBase(SystemClock.elapsedRealtime());// 计时清零
		}
	}

	// 开始录音
	private void startRec() {
		if (recType == 2) {
			// 采用AudioRecord
			try {
				recBufSize = android.media.AudioRecord.getMinBufferSize(
						frequency, channel, encodingBitRate);

				audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
						frequency, channel, encodingBitRate, recBufSize);
				audioRecord.startRecording();
				isRecording = true;
				recThread = new Thread(new Runnable() {
					public void run() {
						writeAudioDataToFile();
					}
				}, "AudioRecorder Thread");
				recThread.start();
			} catch (Exception e) {
				e.printStackTrace();
				ToastHelp.showToast(this, "初始化失败，请重新设定录音频率");
			}
		} else if (recType == 1)
		// 采用MediaRecorder
		{
			try {
				tempName = DateHelp.getFormateDate(3);
				recFile = File.createTempFile(tempName, ".wav", SDCard
						.getFileSavePath(getString(R.string.rec_savepath)));/* 创建录音文件 */
				chronometer.setBase(SystemClock.elapsedRealtime());// 设置开始讲时时间
				chronometer.start();// 开始记时
				mediaRec = new MediaRecorder(); // 实例化MediaRecorder对象
				mediaRec.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
				mediaRec.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);// 设置输出文件的格式
				// 指定OutputFormat,我们选择3gp格式
				// MPEG-4:这将指定录制的文件为mpeg-4格式，可以保护Audio和Video
				// RAW_AMR:录制原始文件，这只支持音频录制，同时要求音频编码为AMR_NB
				// THREE_GPP:录制后文件是一个3gp文件，支持音频和视频录制
				mediaRec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);// 设置音频文件的编码
				mediaRec.setOutputFile(recFile.getAbsolutePath());// 设置输出文件的路径
				mediaRec.prepare();// 准备
				mediaRec.start();// 开始
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	// 将音频数据写入文件
	private void writeAudioDataToFile() {
		if (!(SDCard.getFileSavePath(getString(R.string.rec_savepath)) == null)) {
			byte data[] = new byte[recBufSize];
			FileOutputStream os = null;
			try {

				os = new FileOutputStream(tempFilePath);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			int read = 0;
			if (null != os) {
				while (isRecording) {
					read = audioRecord.read(data, 0, recBufSize);
					if (AudioRecord.ERROR_INVALID_OPERATION != read) {
						try {
							os.write(data);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}

				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			ToastHelp.showToast(this, "手机无内存卡，请插入！");
		}

	}

	// 停止录音
	private void stopRecord() {
		if (recType == 2) {
			if (null != audioRecord) {
				isRecording = false;
				audioRecord.stop();
				audioRecord.release();
				audioRecord = null;
				recThread = null;
			}
			// 保存录音文件到sdcard
			String fileName = DateHelp.getFormateDate(3);
			saveFilePath = SDCard
					.getFileSavePath(getString(R.string.rec_savepath))
					+ "/"
					+ fileName + ".wav";
			copyWaveFile(tempFilePath, saveFilePath);
			freshListView();
			deleteTempFile();
		} else if (recType == 1) {
			if (mediaRec != null) {
				mediaRec.stop();/* 停止录音 */
				mediaRec.release();/* 释放MediaRecorder */
				mediaRec = null;
			}
			freshListView();
		}

	}

	// 删除临时文件
	private void deleteTempFile() {
		File file = new File(tempFilePath);
		file.delete();
	}

	private void copyWaveFile(String inFilename, String outFilename) {
		FileInputStream in = null;
		FileOutputStream out = null;
		long totalAudioLen = 0;
		long totalDataLen = totalAudioLen + 36;
		long longSampleRate = frequency;
		int channels = 2;
		long byteRate = recorder_bpp * frequency * channels / 8;

		byte[] data = new byte[recBufSize];

		try {
			in = new FileInputStream(inFilename);
			out = new FileOutputStream(outFilename);
			totalAudioLen = in.getChannel().size();
			totalDataLen = totalAudioLen + 36;
			WriteWaveFileHeader(out, totalAudioLen, totalDataLen,
					longSampleRate, channels, byteRate);

			while (in.read(data) != -1) {
				out.write(data);
			}

			in.close();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void WriteWaveFileHeader(FileOutputStream out, long totalAudioLen,
			long totalDataLen, long longSampleRate, int channels, long byteRate)
			throws IOException {

		byte[] header = new byte[44];

		header[0] = 'R'; // RIFF/WAVE header
		header[1] = 'I';
		header[2] = 'F';
		header[3] = 'F';
		header[4] = (byte) (totalDataLen & 0xff);
		header[5] = (byte) ((totalDataLen >> 8) & 0xff);
		header[6] = (byte) ((totalDataLen >> 16) & 0xff);
		header[7] = (byte) ((totalDataLen >> 24) & 0xff);
		header[8] = 'W';
		header[9] = 'A';
		header[10] = 'V';
		header[11] = 'E';
		header[12] = 'f'; // 'fmt ' chunk
		header[13] = 'm';
		header[14] = 't';
		header[15] = ' ';
		header[16] = 16; // 4 bytes: size of 'fmt ' chunk
		header[17] = 0;
		header[18] = 0;
		header[19] = 0;
		header[20] = 1; // format = 1
		header[21] = 0;
		header[22] = (byte) channels;
		header[23] = 0;
		header[24] = (byte) (longSampleRate & 0xff);
		header[25] = (byte) ((longSampleRate >> 8) & 0xff);
		header[26] = (byte) ((longSampleRate >> 16) & 0xff);
		header[27] = (byte) ((longSampleRate >> 24) & 0xff);
		header[28] = (byte) (byteRate & 0xff);
		header[29] = (byte) ((byteRate >> 8) & 0xff);
		header[30] = (byte) ((byteRate >> 16) & 0xff);
		header[31] = (byte) ((byteRate >> 24) & 0xff);
		header[32] = (byte) (2 * 16 / 8); // block align
		header[33] = 0;
		header[34] = recorder_bpp; // bits per sample
		header[35] = 0;
		header[36] = 'd';
		header[37] = 'a';
		header[38] = 't';
		header[39] = 'a';
		header[40] = (byte) (totalAudioLen & 0xff);
		header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
		header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
		header[43] = (byte) ((totalAudioLen >> 24) & 0xff);

		out.write(header, 0, 44);
	}

	public int getLayoutInt() {
		return R.layout.audiorecordview;
	}

	public void initControls() {
		initView();
		mainFrame.setBackgroundResource(R.drawable.background);
	}

	public String setTitle() {
		return "录音选择";
	}

	// 调用系统播放器，播放录音
	private void playRec(File file) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file), "audio");/* 设置文件类型 */
		startActivity(intent);
	}

	@Override
	protected void onDestroy() {
		// isStopThread();
		// this.unregisterReceiver(broadcastReceiver);
		// playService.destory();
		// this.unbindService(sconnection);
		super.onDestroy();
	}

	public void back_deal() {
		AlertHelp.ShowAlert(this, "确认返回？",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
	}

	@Override
	public void KEYCODE_BACK() {
		back_deal();
	}

	@Override
	public void refresh(Object... param) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void refreshForNewTask(int TaskId,Object... param){
	}
}
